using System.Collections.Generic;
using Tycho.Parser.Tokens;
using Tycho.Runtime;

namespace Tycho.Compiler {
    public class Term : StructureObject {
        private SourceLocation InternalSourceLocation;

        public Term (SourceLocation sourceLocation, params AnyObject [] fields) : base (RuntimeModule.Null, fields) {
            InternalSourceLocation = sourceLocation;
        }

        public override SourceLocation SourceLocation {
            get { return InternalSourceLocation; }
            set { InternalSourceLocation = value; }
        }

        public override bool HasSourceLocation {
            get {
                return true;
            }
        }

        public override string ToString (HashSet<AnyObject> done) {
            if (ToStringNoRecurse (done)) {
                string result = "term {";
                bool first = true;

                foreach (KeyValuePair<AnyObject, AnyObject> value in Fields) {
                    if (value.Key != Symbols.ParserSourceLocation) {
                        if (!first) {
                            result += ", ";
                        }

                        AnyObject key = value.Key;
                        string name = GetFieldName (done, key);
                        if (value.Value.IsNull) {
                            result += name;
                        } else {
                            result += name + ": " + value.Value.ToString (done);
                        }

                        first = false;
                    }
                }

                return result + "}";
            } else {
                return "...";
            }
        }

        private static string GetFieldName (HashSet<AnyObject> done, AnyObject key) {
            if (key is Symbol) {
                var symbol = (Symbol) key;
                if (symbol.Namespace == Namespaces.Parser) {
                    return symbol.Name;
                }
            }

            return key.ToString (done);
        }
    }
}